from django.shortcuts import render
from django_redis import get_redis_connection
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter

# Create your views here.
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from books.models import Books, BooksCategory
from books.serializers import BookSerializer, BookIndexSerializer, BookHisrotySerializer
from orders.models import OrderBooks


class BooksListView(ListAPIView):
    """
    sku列表数据
    """
    serializer_class = BookSerializer
    filter_backends = (OrderingFilter,)
    ordering_fields = ('create_time', 'scorce', 'comments')

    def get_queryset(self):
        category_id = self.kwargs['pk']
        return Books.objects.filter(category3_id=category_id, is_launched=True)


class BookSerchViewSet(HaystackViewSet):
    """
    Book搜索
    """
    index_models = [Books]

    serializer_class = BookIndexSerializer


class CategoriesView(APIView):
    """获取当前分类信息"""

    def get(self,request, pk):
        cat3 = BooksCategory.objects.get(id=pk)  # 获取三级
        cat2 = cat3.parent  # 自关联获取二级,
        cat1 = cat2.parent  # 自关联获取一级

        # 返回数据
        return Response({
            "cat1": cat1.name,
            "cat2": cat2.name,
            "cat3": cat3.name
        })

class BookHistoryView(CreateAPIView):
    """ 保存用户历史浏览记录 """
    serializer_class = BookHisrotySerializer

    def get(self, request):
        """
        获取用户浏览记录
        :param request:
        :return:
        """
        user_id = request.user.id

        redis_conn = get_redis_connection('history')
        history = redis_conn.lrange("history_{}".format(user_id), 0, 10)

        books = []

        # 为了保持查询出的用户浏览的顺序一致
        for book_id in history:
            sku = Books.objects.get(id=book_id)
            books.append(sku)

        s = BookSerializer(books, many=True)
        return Response(s.data)


class CommentShowView(APIView):
    """展示商品评论"""
    def get(self,request, pk):
        """
        获取商品评论展示
        :param request:
        :return: [{comment.username, comment.comment}]
        """
        # 1.获取商品id
        # skuid = self.kwargs["pk"]
        bookid = pk
        # 2.查询reder_goods表获取订单商品信息
        orderinfos = OrderBooks.objects.filter(book_id=bookid, is_commented=True)
        # 3.定义评论列表
        comment_list = []
        for orderinfo in orderinfos:
            comment = {}
            if orderinfo.is_anonymous:
                username = orderinfo.order.user.username.replace(orderinfo.order.user.username[1:-1],"***")
            else:
                username = orderinfo.order.user.username
            print(username)
            comment["username"] = username
            comment["score"] = orderinfo.score
            comment["comment"] = orderinfo.comment
            comment_list.append(comment)
        return Response(comment_list)




